using System;
using System.ComponentModel;
using ZoneFiveSoftware.Common.Data;
using ZoneFiveSoftware.Common.Data.Fitness;

namespace FilteredStatistics.Controller
{
    class ActivityDataChangedHelper : INotifyPropertyChanged, IDisposable
    {
        public ActivityDataChangedHelper(IActivity activity)
        {
            m_Activity = activity;

            PluginMain.GetApplication().SystemPreferences.PropertyChanged += new PropertyChangedEventHandler(OnSystemPreferencesPropertyChanged);
            m_Activity.DataChanged += new NotifyDataChangedEventHandler(OnActivityDataChanged);

            RegisterCategoryCallback();

            GearSelectionPlugin.Instance.BikeSetupChanged += new GearSelectionPlugin.BikeSetupChangedEventHandler(OnGearChartBikeSetupChanged);
        }

#region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

#endregion
            
#region IDisposable Members

        public void  Dispose()
        {
            PluginMain.GetApplication().SystemPreferences.PropertyChanged -= new PropertyChangedEventHandler(OnSystemPreferencesPropertyChanged);
            m_Activity.DataChanged -= new NotifyDataChangedEventHandler(OnActivityDataChanged);

            UnregisterCategoryCallback();

            GearSelectionPlugin.Instance.BikeSetupChanged -= new GearSelectionPlugin.BikeSetupChangedEventHandler(OnGearChartBikeSetupChanged);
        }

#endregion

        private void OnSystemPreferencesPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName.StartsWith("AnalysisSettings") &&
                SportTracksReflectionUtils.Instance.AnalysisSettingsAvailable)
            {
                TriggerPropertyChangedEvent(SportTracksReflectionUtils.Instance.AnalysisSettings, e.PropertyName);
            }
            else if (e.PropertyName == "DistanceUnits" ||
                     e.PropertyName == "ElevationUnits")
            {
                if (m_Activity.Category.UseSystemLengthUnits)
                {
                    TriggerPropertyChangedEvent(PluginMain.GetApplication().SystemPreferences, e.PropertyName);
                }
            }
        }

        private void OnActivityDataChanged(object sender, NotifyDataChangedEventArgs e)
        {
            if (e.Action == NotifyDataChangedAction.PropertySet)
            {
                foreach (string property in e.PropertiesSet)
                {
                    TriggerPropertyChangedEvent(m_Activity, "Activity." + property);
                }
            }
            else if (e.Action == NotifyDataChangedAction.Add ||
                     e.Action == NotifyDataChangedAction.Remove ||
                     e.Action == NotifyDataChangedAction.Replace)
            {
                int i = 0;
                ++i;
            }
        }

        private void OnCategoryDataChanged(object sender, NotifyDataChangedEventArgs e)
        {
            if (e.Action == NotifyDataChangedAction.PropertySet)
            {
                IActivityCategory modifiedCategory = e.NewItems[0] as IActivityCategory;

                if (IsInActivityCategoryHierarchy(m_Activity, modifiedCategory))
                {
                    foreach (string property in e.PropertiesSet)
                    {
                        TriggerPropertyChangedEvent(m_Activity.Category, "ActivityCategory." + property);
                    }
                }
            }
        }

        private void OnGearChartBikeSetupChanged(object sender, string setupId)
        {
            if (m_Activity != null)
            {
                foreach (IEquipmentItem equipment in m_Activity.EquipmentUsed)
                {
                    if (equipment.ReferenceId.Equals(setupId))
                    {
                        TriggerPropertyChangedEvent(setupId, "BikeSetup");
                        break;
                    }
                }
            }
        }

        private void RegisterCategoryCallback()
        {
            foreach(IActivityCategory category in PluginMain.GetApplication().Logbook.ActivityCategories)
            {
                category.DataChanged += new NotifyDataChangedEventHandler(OnCategoryDataChanged);
            }
        }

        private void UnregisterCategoryCallback()
        {
            foreach (IActivityCategory category in PluginMain.GetApplication().Logbook.ActivityCategories)
            {
                category.DataChanged -= new NotifyDataChangedEventHandler(OnCategoryDataChanged);
            }
        }

        private void TriggerPropertyChangedEvent(object modifiedObject, string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(modifiedObject, new PropertyChangedEventArgs(propertyName));
            }
        }

        private bool IsInActivityCategoryHierarchy(IActivity activity, IActivityCategory category)
        {
            IActivityCategory currentCategory = activity.Category;

            do
            {
                if (category == currentCategory)
                {
                    return true;
                }
                else if (!currentCategory.UseParentSettings)
                {
                    return false;
                }

                currentCategory = currentCategory.Parent;
            }
            while (currentCategory != null);

            return false;
        }

        private IActivity m_Activity = null;
    }
}
